package simpleservlet;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.HttpRequest;

import java.util.Map;

@ChannelHandler.Sharable
public class TomcatHandler extends ChannelInboundHandlerAdapter {

    private final Map<String, Servlet> servletMapping;
    public TomcatHandler(Map<String,Servlet> servletMapping) {
        this.servletMapping = servletMapping;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        //如果是http请求
        if(msg instanceof HttpRequest) {
            System.out.println("inbound handler ...");
            HttpRequest request = (HttpRequest)msg;

            //转交自定义实现的httprequest和httpresponse
            NettyRequest request1 = new NettyRequest(ctx,request);
            NettyResponse response = new NettyResponse(ctx,request);

            String url = request1.getUrl();
            System.out.println("request url:" + url);
            if(servletMapping.containsKey(url)) {
                System.out.println("start service");
                servletMapping.get(url).service(request1,response);
            } else {
                System.out.println("not found");
                response.write("404 - not found");
            }
        }
    }

    //启动服务
    public static void main(String[] args) throws Exception {
        new NettyTomcat().start();
    }
}